<template>
    <PageWrapper>
      <n-card :bordered="false" class="mb-3 proCard">
        <n-space align="center">
          <n-input-group style="width: 1280px">
            <div style="margin-left: 10px !important;display: flex;align-items: center;">
              <n-input
                style="width: 100%;margin-left: 20px;"
                v-model:value="params.name"
                clearable
                placeholder="请输入门店名称"
                @keyup.enter="reloadTable"
              />
              <n-input
                style="width: 100%;margin-left: 20px;"
                v-model:value="params.full_address"
                clearable
                placeholder="请输入地址"
                @keyup.enter="reloadTable"
              />
              <div style="margin-left: 10px !important;display: flex;align-items: center;">
                <n-select v-model:value="params.store_type" placeholder="请选择门店类型" style="width: 200px;margin-left: 20px;" :options="options" clearable />
              </div>
              <n-input
                style="width: 100%;margin-left: 20px;"
                v-model:value="params.charger_agents_name"
                clearable
                placeholder="请输入代理商名称"
                @keyup.enter="reloadTable"
              />
              <n-input
                style="width: 100%;margin-left: 20px;"
                v-model:value="params.charger_bussiness_name"
                clearable
                placeholder="请输入商户名称"
                @keyup.enter="reloadTable"
              />
              <n-input
                style="width: 100%;margin-left: 20px;"
                v-model:value="params.charger_yuangong_name"
                clearable
                placeholder="请输入员工名称"
                @keyup.enter="reloadTable"
              />
            </div>
            <n-button type="primary" style="margin-left: 40px !important;" @click="reloadTable">
              <template #icon>
                <n-icon>
                  <SearchOutlined />
                </n-icon>
              </template>
              查询
            </n-button>
          </n-input-group>
        </n-space>
      </n-card>
      <n-card :bordered="false" class="proCard">
        <BasicTable
          :columns="columns"
          :request="loadDataTable"
          :row-key="(row) => row.id"
          ref="basicTableRef"
          :actionColumn="actionColumn"
          @update:checked-row-keys="onCheckedRow"
          :scroll-x="3500"
        >
          <template #tableTitle>
            <n-space align="center">
              <n-button type="primary" @click="openCreateDrawer">
                <template #icon>
                  <n-icon>
                    <FileAddOutlined />
                  </n-icon>
                </template>
                添加
              </n-button>
              <n-button type="primary" @click="openDailishang">
                批量分配
              </n-button>
            </n-space>
          </template>
        </BasicTable>
      </n-card>

      <n-modal v-model:show="showModal">
        <n-card
          style="width: 600px"
          title="批量分配"
          :bordered="false"
          size="huge"
          role="dialog"
          aria-modal="true"
        >
          <n-form
            :model="formParams1"
            ref="formRef"
            label-placement="left"
            :label-width="100"
          >
            <n-form-item label="门店名称：" path="charger_number">
              {{rowKeysName}}
            </n-form-item>

            <n-form-item label="归属代理商：">
              <n-input placeholder="请选择归属代理商" disabled v-model:value="formParams1.charger_agents_name" />
              <n-button type="primary" @click="handleAgent" ghost>
                选择代理商
              </n-button>
            </n-form-item>

            <n-form-item label="归属员工">
              <n-input placeholder="请选择归属员工" disabled v-model:value="formParams1.charger_yuangong_name" />
              <n-button type="primary" @click="handleyuangong" ghost>
                选择员工
              </n-button>
            </n-form-item>

            <n-form-item label="归属商户">
              <n-input placeholder="请选择归属商户" disabled v-model:value="formParams1.charger_bussiness_name" />
              <n-button type="primary" @click="handleBusinesses" ghost>
                选择商户
              </n-button>
            </n-form-item>
            
          </n-form>
          <template #footer>
            <n-space>
              <n-button type="primary" :loading="subLoading" @click="formSubmit">提交</n-button>
            </n-space>
          </template>

        </n-card>
      </n-modal>

      <n-modal v-model:show="showModalagent">
        <n-card
          style="width: 600px"
          title="选择代理商"
          :bordered="false"
          size="huge"
          role="dialog"
          aria-modal="true"
        >
          <div style="display: flex;align-items: center;">
                <div style="width: 50px;">名称：</div>
                  <n-input
                    style="width: 50%;"
                    v-model:value="chargerParams.name"
                    clearable
                    placeholder="请输入名称"
                  />
                  <n-button style="margin-left: 10px" @click="chaSearchBut">搜索</n-button>
            </div>
          <n-table :bordered="false" :single-line="false">
            <thead>
            <tr>
              <th>代理商名称</th>
              <th>代理商账号</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(item,index) in agentAll" :key="index">
              <td>{{item.nickname}}</td>
              <td>{{item.username}}</td>
              <td><n-button type="primary" @click="selectAgent(item)">选择</n-button></td>
            </tr>
          </tbody>
          </n-table>
          <n-pagination
              v-model:page="chargerParams.page"
              v-model:page-size="chargerParams.pageSize"
              :page-count="chargerParams.totalPage"
              show-size-picker
              :page-sizes="[10, 20, 30, 40]"
              :on-update-page="chargerChangePage"
              :on-update-page-size="chargerChangePagesize"
            />
        </n-card>
      </n-modal>

      <n-modal v-model:show="businessesModal">
        <n-card
          style="width: 600px"
          title="选择商户"
          :bordered="false"
          size="huge"
          role="dialog"
          aria-modal="true"
        >
            <div style="display: flex;align-items: center;">
                <div style="width: 50px;">名称：</div>
                  <n-input
                    style="width: 50%;"
                    v-model:value="stationParams.name"
                    clearable
                    placeholder="请输入名称"
                  />
                  <n-button style="margin-left: 10px" @click="staSearchBut">搜索</n-button>
            </div>
          <n-table :bordered="false" :single-line="false">
            <thead>
              <tr>
                <th>商户名称</th>
                <th>商户账号</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(item,index) in businessesAll" :key="index">
                <td>{{item.nickname}}</td>
                <td>{{item.username}}</td>
                <td><n-button type="primary" @click="selectBusinesses(item)">选择</n-button></td>
              </tr>
            </tbody>
          </n-table>
          <n-pagination
              v-model:page="stationParams.page"
              v-model:page-size="stationParams.pageSize"
              :page-count="stationParams.totalPage"
              show-size-picker
              :page-sizes="[10, 20, 30, 40]"
              :on-update-page="stationChangePage"
              :on-update-page-size="stationChangePagesize"
            />
        </n-card>
      </n-modal>

      <n-modal v-model:show="yuangongModal">
        <n-card
          style="width: 600px"
          title="选择员工"
          :bordered="false"
          size="huge"
          role="dialog"
          aria-modal="true"
        >
          <div style="display: flex;align-items: center;">
            <div style="width: 50px;">名称：</div>
            <n-input
              style="width: 50%;"
              v-model:value="yuangongParams.name"
              clearable
              placeholder="请输入名称"
            />
            <n-button style="margin-left: 10px" @click="yuangongSearchBut">搜索</n-button>
          </div>
          <n-table :bordered="false" :single-line="false">
            <thead>
              <tr>
                <th>员工名称</th>
                <th>员工账号</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(item,index) in yuangongAll" :key="index">
                <td>{{item.nickname}}</td>
                <td>{{item.username}}</td>
                <td><n-button type="primary" @click="selectyuangong(item)">选择</n-button></td>
              </tr>
            </tbody>
          </n-table>
          <n-pagination
              v-model:page="yuangongParams.page"
              v-model:page-size="yuangongParams.pageSize"
              :page-count="yuangongParams.totalPage"
              show-size-picker
              :page-sizes="[10, 20, 30, 40]"
              :on-update-page="yuangongChangePage"
              :on-update-page-size="yuangongChangePagesize"
            />
        </n-card>
      </n-modal>

      <n-modal v-model:show="showModalwifi">
        <n-card
          style="width: 600px"
          title="WIFI管理"
          :bordered="false"
          size="huge"
          role="dialog"
          aria-modal="true"
        >
          <div style="display: flex;align-items: center; margin-bottom: 10px">
            <n-button @click="wifixinzeng">新增</n-button>
          </div>
          <n-table :bordered="false" :single-line="false">
            <thead>
            <tr>
              <th>名称</th>
              <th>密码</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(item,index) in wifiAll" :key="index">
              <td>{{item.username}}</td>
              <td>{{item.password}}</td>
              <td>
                <n-button strong secondary type="primary" @click="editwifi(item)">编辑</n-button>
                <n-button strong secondary type="error" style="margin-left: 10px;" @click="delwifi(item)">删除</n-button>
              </td>
            </tr>
          </tbody>
          </n-table>
          <n-pagination
              v-model:page="wifiParams.page"
              v-model:page-size="wifiParams.pageSize"
              :page-count="wifiParams.totalPage"
              show-size-picker
              :page-sizes="[10, 20, 30, 40]"
              :on-update-page="wifiChangePage"
              :on-update-page-size="wifiChangePagesize"
            />
        </n-card>
      </n-modal>
  
      <CreateDrawer
        ref="createDrawerRef"
        :title="drawerTitle"
        :roleList="roleData"
        @change="reloadTable"
      />

      <CreateDrawer1
        ref="createDrawerRef1"
        :title="drawerTitle1"
        :roleList="roleData"
        @change="reloadTable"
      />

      <CreateDrawerwifi
        ref="createDrawerRefwifi"
        :title="drawerTitlewifi"
        :roleList="roleData"
        @change="reloadTable"
      />

    </PageWrapper>

  </template>
  
  <script lang="ts" setup>
    import { h, reactive, ref, onMounted } from 'vue';
    import { useMessage } from 'naive-ui';
    import { BasicColumn, BasicTable, TableAction } from '@/components/Tablex';
    import { stationlist,stationChange } from '@/api/device/station';
    import { bussinessCharger,getStoreTypeList,yuangongCharger,getallwifiList,wifiDel } from '@/api/device/charger';
    import { FileAddOutlined, SearchOutlined } from '@vicons/antd';
    import CreateDrawer from './CreateDrawer.vue';
    import CreateDrawer1 from './CreateDrawer1.vue';
    import CreateDrawerwifi from './CreateDrawerwifi.vue';
    import { columns } from './columns';
    import { getallagentList1 } from '@/api/system/user';
  
    const message = useMessage();
    const basicTableRef = ref();
    const rowKeys = ref([]);
    const tableData = ref();
    const createDrawerRef = ref();
    const createDrawerRef1 = ref();
    const createDrawerRefwifi = ref();
    const drawerTitle = ref('添加门店');
    const drawerTitle1 = ref('计费规则');
    const drawerTitlewifi = ref('WIFI管理');
    const roleData = ref([]);
    const rowKeysName = ref([]);
    const subLoading = ref(false);
    const formRef: any = ref(null);
    const agentAll = ref([{
      nickname: '',
      username: '',
    }]);
    const chargerParams = ref({
      name:'',
      page:1,
      pageSize:10,
      totalPage:1,
    });

    const stationParams = ref({
      name:'',
      page:1,
      pageSize:10,
      totalPage:1,
      charger_agents_id:''
    });

    const yuangongParams = ref({
      name:'',
      page:1,
      pageSize:10,
      totalPage:1,
      charger_agents_id:''
    });

    const wifiParams = ref({
      station_id: '',
      page:1,
      pageSize:10,
      totalPage:1,
    });

    const options = ref([{}]);
    const showModal = ref(false);
    const showModalagent = ref(false);
    const businessesModal = ref(false);
    const yuangongModal = ref(false);
    const showModalwifi = ref(false);
    const businessesAll = ref([{
      nickname: '',
      username: '',
    }]);

    const yuangongAll = ref([{
      nickname: '',
      username: '',
    }]);

    const wifiAll = ref([{
      username: '',
      password: '',
    }]);
  
    const params = reactive({
      name: '',
      full_address: '',
      store_type: null,
      charger_agents_name: '',
      charger_bussiness_name: '',
      charger_yuangong_name: '',
    });
  
    const actionColumn: BasicColumn = reactive({
      width: 230,
      title: '操作',
      key: 'action',
      fixed: 'right',
      align: 'center',
      render(record) {
        if(record.chargingline == 1){
          return h(TableAction as any, {
            actions: [
              {
                label: '编辑',
                onClick: handleEdit.bind(null, record),
              }, {
                label: '计费规则',
                onClick: handleBilling.bind(null, record),
              }, {
                label: 'WIFI管理',
                onClick: handleWIFI.bind(null, record),
              },
            ],
          });
        }else{
          return h(TableAction as any, {
            actions: [
              {
                label: '编辑',
                onClick: handleEdit.bind(null, record),
              }, {
                label: '计费规则',
                onClick: handleBilling.bind(null, record),
              },
            ],
          });
        }
      },
    });
  
    const loadDataTable = async (res) => {
      const result = await stationlist({ ...params, ...res });
      tableData.value = result.list;
      return result;
    };
  
    function onCheckedRow(keys) {
      rowKeys.value = keys;
      rowKeysName.value = tableData.value.filter((item) => {
        return keys.includes(item.id);
      })
      .map((item) => {
        return item.name;
      })
      .join(',');
    }
  
    function formSubmit() {
      formRef.value.validate((errors) => {
        if (!errors) {
          if(formParams1.value.ids.length==0){
            message.error('请选择分配的门店');
          }

          let formParams = formParams1.value;
          formParams.ids = formParams1.value.ids.join(",");

          stationChange(formParams).then(()=>{
            showModal.value = false;
            message.success('分配成功');
            reloadTable();
          });
        } else {
          message.error('请填写完整信息');
        }
      });
    }

    function reloadTable() {
      basicTableRef.value.reload();
    }
  
    function openCreateDrawer() {
      const { openDrawer } = createDrawerRef.value;
      openDrawer();
    }

    function handleBilling(record: Recordable) {
      drawerTitle1.value = '修改计费规则';
      const { openDrawer } = createDrawerRef1.value;

      openDrawer(record.id,record.billingstatus,record.kbillingstatus);
    }

    function handleWIFI(record: Recordable) {
      let id = record.id;
      wifiParams.value.station_id = id;
      wifiAll.value = [];
      getallwifiList(wifiParams.value).then((res)=>{
        wifiParams.value.totalPage = res.totalPage;
        wifiAll.value = res.list;

        showModalwifi.value = true;
      });
    }

    function wifixinzeng() {
      drawerTitlewifi.value = '新增WIFI';
      const { openDrawer } = createDrawerRefwifi.value;
      let station_id = wifiParams.value.station_id;
      showModalwifi.value = false;
      openDrawer('',station_id);
    }

    function editwifi(item) {
      drawerTitle.value = '编辑WIFI';
      const { openDrawer } = createDrawerRefwifi.value;
      showModalwifi.value = false;
      openDrawer(item.id,item.station_id);
    }

    function delwifi(item) {
      wifiDel({ id: item.id }).then(() => {
        message.success('删除成功');

        getallwifiList(wifiParams.value).then((res)=>{
          wifiParams.value.totalPage = res.totalPage;
          wifiAll.value = res.list;

        });
        reloadTable();
      });
    }
  
    function handleEdit(record: Recordable) {
      drawerTitle.value = '编辑门店';
      const { openDrawer } = createDrawerRef.value;
      openDrawer(record.id);
    }

    function openDailishang(){
      if(rowKeys.value.length == 0){
        message.success('请选择门店信息');
      }else{
        formParams1.value.ids = rowKeys.value;
        showModal.value = true;
      }
    }

    const defaultValueRef = () => ({
      ids: [],
      charger_agents_name: '',
      charger_agents_id: 0,
      charger_bussiness_id: 0,
      charger_bussiness_name: '',
      charger_yuangong_id: 0,
      charger_yuangong_name: ''
    });

    const formParams1 = ref(defaultValueRef());
    function handleAgent() {
      showModalagent.value = true;
    }

    function handleBusinesses(){
      if(formParams1.value.charger_agents_name == ''){
        message.error('请选择代理商信息');
      }else{
        businessesModal.value = true;
      }
    }

    function handleyuangong(){
      yuangongModal.value = true;
    }

    function selectBusinesses(item){
      //商户id
      formParams1.value.charger_bussiness_id = item.id;
      //商户名称
      formParams1.value.charger_bussiness_name = item.username;
      
      businessesModal.value = false;
    }

    //选择员工
    function selectyuangong(item){
      //员工id
      formParams1.value.charger_yuangong_id = item.id;
      //员工名称
      formParams1.value.charger_yuangong_name = item.username;
      
      yuangongModal.value = false;
    }

    //批量修改
    async function selectAgent(item){
      //代理商
      formParams1.value.charger_agents_id = item.id;
      formParams1.value.charger_agents_name = item.username;

      //商户
      formParams1.value.charger_bussiness_id = 0;
      formParams1.value.charger_bussiness_name = '';

      //员工
      formParams1.value.charger_yuangong_id = 0;
      formParams1.value.charger_yuangong_name = '';

      stationParams.value.charger_agents_id = item.id;
      //查询商户
      var result = await bussinessCharger(stationParams.value);
      stationParams.value.totalPage = result.totalPage;
      businessesAll.value = result.list;

      //查询员工
      yuangongParams.value.charger_agents_id = item.id;
      var result1 = await yuangongCharger(yuangongParams.value);
      yuangongParams.value.totalPage = result1.totalPage;
      yuangongAll.value = result1.list;

      showModalagent.value = false;
    }

    //代理商分页
    async function chargerChangePage(e){
      //改变一下页数
      chargerParams.value.page = e;
      //重新请求一下接口
      var agentAll1 = await getallagentList1(chargerParams.value);
      chargerParams.value.totalPage = agentAll1.totalPage;
      agentAll.value = agentAll1.list;
    }
    async function chargerChangePagesize(e){
      //改变条数
      chargerParams.value.pageSize = e;

      var agentAll1 = await getallagentList1(chargerParams.value);
      chargerParams.value.totalPage = agentAll1.totalPage;
      agentAll.value = agentAll1.list;
    }

    //商家分页
    async function stationChangePage(e){
      //改变一下页数
      stationParams.value.page = e;
      //重新请求一下接口
      var result = await bussinessCharger(stationParams.value);
      stationParams.value.totalPage = result.totalPage;
      businessesAll.value = result.list;
    }
    async function stationChangePagesize(e){
      //改变条数
      stationParams.value.pageSize = e;

      var result = await bussinessCharger(stationParams.value);

      stationParams.value.totalPage = result.totalPage;
      businessesAll.value = result.list;
    }

    //商家搜索
    async function staSearchBut(){
      var result = await bussinessCharger(stationParams.value);
      stationParams.value.totalPage = result.totalPage;
      businessesAll.value = result.list;
    }
    //代理商搜索
    async function chaSearchBut(){
      var agentAll1 = await getallagentList1(chargerParams.value);
      chargerParams.value.totalPage = agentAll1.totalPage;
      agentAll.value = agentAll1.list;
    }

    //员工搜索
    async function yuangongSearchBut(){
      var result = await yuangongCharger(yuangongParams.value);
      yuangongParams.value.totalPage = result.totalPage;
      yuangongAll.value = result.list;
    }
    //员工分页
    async function yuangongChangePage(e){
      //改变一下页数
      yuangongParams.value.page = e;
      //重新请求一下接口
      var result = await yuangongCharger(yuangongParams.value);
      yuangongParams.value.totalPage = result.totalPage;
      yuangongAll.value = result.list;
    }
    async function yuangongChangePagesize(e){
      //改变条数
      yuangongParams.value.pageSize = e;

      var result = await yuangongCharger(yuangongParams.value);

      yuangongParams.value.totalPage = result.totalPage;
      yuangongAll.value = result.list;
    }

    //wifi分页
    async function wifiChangePage(e){
      //改变一下页数
      wifiParams.value.page = e;
      //重新请求一下接口
      var wifiAll1 = await getallwifiList(wifiParams.value);
      wifiParams.value.totalPage = wifiAll1.totalPage;
      wifiAll.value = wifiAll1.list;
    }
    async function wifiChangePagesize(e){
      //改变条数
      wifiParams.value.pageSize = e;

      var wifiAll1 = await getallwifiList(wifiParams.value);
      wifiParams.value.totalPage = wifiAll1.totalPage;
      wifiAll.value = wifiAll1.list;
    }

    onMounted(async () => {
      //查询一下所有的代理商
      agentAll.value = [];
      var agentAll1 = await getallagentList1(chargerParams.value);
      chargerParams.value.totalPage = agentAll1.totalPage;
      agentAll.value = agentAll1.list;

      var result1 = await yuangongCharger(yuangongParams.value);
      yuangongParams.value.totalPage = result1.totalPage;
      yuangongAll.value = result1.list;

      //查询所有的门店类型
      var storeType = await getStoreTypeList({});
      if(storeType){
        options.value = [];
        for(let i=0;i<storeType.length;i++){
          options.value.push({
            label: storeType[i].name,
            value: storeType[i].id,
          })
        }
      }
    });
  </script>
  
  <style lang="less" scoped></style>
  